<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { getCommonStudyTreeTags } from '@/api/study/studySquare';
import { message } from 'ant-design-vue';
import axios from 'axios';
import type { StudyTreeItem } from '@/views/Square/LearningSquare/SkillTree/home/types/StudyTreeItem';
import SkillTreeCard from '@/views/Square/LearningSquare/SkillTree/home/components/SkillTreeCard.vue';

const searchQuery = ref<string>('');
const filterOptions = ref<{ tagId: string, tagName: string }[]>([]);
const selectedFilter = ref<string>('全部');
const columnNum = ref<number>(4);
const currentPageIndex = ref<number>(1);
const studyTreeItems = ref<StudyTreeItem[]>([]);

const onAdviceBtnClicked = () => {
  window.open(import.meta.env.VITE_ADVICE_URL, '_blank');
}

// 获取标签分类
const fetchFilterOptions = async () => {
  try {
    const response = await getCommonStudyTreeTags();
    filterOptions.value = [{ tagId: '', tagName: '全部' }, ...response];
  }
  catch (error) {
    console.error('Failed to fetch categories:', error);
    message.error('请求标签时出现错误');
  }
};

// 获取 Cookie 中的 Access Token 的辅助函数
const getCookieValue = (name: string): string | null => {
  const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
  return match ? decodeURIComponent(match[2]) : null;
};

const fetchStudyTreeMetaData = async () => {
  const accessToken_java = getCookieValue('access_token_lf');
  if (!accessToken_java) {
    message.error('未检测到访问令牌');
    return;
  }

  const params = {
    tags: (selectedFilter.value === '全部' ? '' : selectedFilter.value) || '',
    page: currentPageIndex.value.toString(),
    size: '100',
    keyword: searchQuery.value || '',
  };

  try {
    const response = await axios.get('/java/teacher/study_tree_json', {
      headers: {
        "Authorization": `Bearer ${accessToken_java}`,
        'Content-Type': 'application/json',
      },
      params,
    });

    if (response.status === 200 && response.data?.data) {
      const studyTreeData: StudyTreeItem[] = await Promise.all(
        response.data.data.map(async (item: StudyTreeItem) => {
          // 对图片URL进行检验
          if (item.imageUrl && !item.imageUrl.startsWith('http')) {
            try {
              const urlResponse = await axios.get('/java/teacher/study_tree_json/getUrl', {
                params: { filename: item.imageUrl },
                headers: {
                  "Authorization": `Bearer ${accessToken_java}`,
                  'Content-Type': 'application/json',
                },
              });
              if (urlResponse.data?.data)
                item.imageUrl = urlResponse.data.data;
            }
            catch (urlError) {
              console.error('Failed to fetch image URL:', urlError);
              item.imageUrl = ''; // 或者设置为默认图片
            }
          }
          return item;
        }),
      );
      studyTreeItems.value = studyTreeData;
    }
    else {
      message.error('获取技能树数据失败');
    }
  }
  catch (error) {
    console.error('Request failed:', error);
    message.error('获取技能树数据时出现错误');
  }
};

// 标签过滤器点击事件
const onFilterBtnClicked = (tagName: string) => {
  selectedFilter.value = tagName;
  currentPageIndex.value = 1;
  fetchStudyTreeMetaData();
}

const onSearchBtnClicked = () => {
  currentPageIndex.value = 1;
  fetchStudyTreeMetaData();
}

onMounted(() => {
  fetchFilterOptions();
  fetchStudyTreeMetaData();
});
</script>

<template>
  <a-layout v-show="$route.meta.showHome" class="home-layout">
    <div class="flex flex-row justify-between items-center mx-4 my-2">
      <!-- 面包屑导航 -->
      <a-breadcrumb class="text-3xl font-bold flex items-center gap-2">
        <a-breadcrumb-item>
          <router-link to="/user/learningNew/skill-tree" style="height: 100%;">
            学习广场
          </router-link>
        </a-breadcrumb-item>

        <a-breadcrumb-item class="flex items-center relative">
          技能树
          <img
            src="@/assets/title_star.svg"
            alt="技能树"
            class="w-6 h-6 absolute -right-6"
          >
        </a-breadcrumb-item>
      </a-breadcrumb>

      <div class="flex flex-row gap-2">
        <a-button type="primary" style="width: 30%;" @click="onAdviceBtnClicked">
          提建议
        </a-button>
        <!-- 搜索框 -->
        <a-input-search
          v-model:value="searchQuery"
          placeholder="搜索技能树"
          :enter-button="true"
          @search="onSearchBtnClicked"
        />
      </div>
    </div>

    <!-- 标签过滤器 -->
    <a-flex style="flex-wrap: wrap; gap: 0.5rem; margin: 0rem 1rem;">
      <a-button
        v-for="option in filterOptions"
        :key="option.tagId"
        :type="option.tagName === selectedFilter ? 'primary' : 'default'"
        @click="onFilterBtnClicked(option.tagName)"
      >
        {{ option.tagName }}
      </a-button>
    </a-flex>

    <!-- 技能树Market -->
    <div style="flex: 1; overflow: auto; margin-top: 1rem; margin-bottom: 0.5rem;">
      <!-- 先使用一层div包裹，再使用a-row和a-col -->
      <div style="margin-left: 1rem; margin-right: 1rem;">
        <a-row :gutter="[10, 10]">
          <a-col v-for="item in studyTreeItems" :key="item.id" :span="24 / columnNum">
            <SkillTreeCard :study-tree-item="item" />
          </a-col>
        </a-row>
      </div>
    </div>
  </a-layout>

  <RouterView v-show="!$route.meta.showHome" />
</template>

<style scoped lang="scss">
.home-layout {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: transparent;
}
</style>
